//
//  KQMessageTextContent.swift
//  JChat
//
//  Created by JIGUANG on 2017/3/9.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import YYImage
open class KQMessageTextContent: NSObject, KQMessageContentType {
    public weak var delegate: KQMessageDelegate?
    public override init() {
        let text = "this is a test text"
        self.text = NSAttributedString(string: text)
        self.originalText = NSAttributedString(string: text)
        super.init()
        self.parse()
    }
    public init(text: String) {
        self.text = NSAttributedString(string: text)
        self.originalText = NSAttributedString(string: text)
        super.init()
        self.parse()
    }
    public init(attributedText: NSAttributedString) {
        self.text = attributedText
        self.originalText = attributedText
        super.init()
        self.parse()
    }
    
    open class var viewType: KQMessageContentViewType.Type {
        return KQMessageTextContentView.self
    }
    open var layoutMargins: UIEdgeInsets = .init(top: 9, left: 10, bottom: 9, right: 10)
    
    open var text: NSAttributedString
    open var originalText: NSAttributedString
    
    open func sizeThatFits(_ size: CGSize) -> CGSize {
        
        let mattrSize = self.text.boundingRect(with: CGSize(width: 250.0, height: Double(MAXFLOAT)), options: [.usesLineFragmentOrigin,.usesFontLeading], context: nil)
        return .init(width: max(mattrSize.width, 15), height: max(mattrSize.height, 20))
    }
    
    private func parse () {
    
        let mattr = NSMutableAttributedString(attributedString: self.text)
        mattr.addAttribute(NSAttributedString.Key.font, value: UIFont(name: KQCHAT_FONT_NAME, size: 16)!, range: NSMakeRange(0, mattr.length))
        //解析富文本
        let attributedString = TSChatTextParser.parseText(mattr, font: UIFont(name: KQCHAT_FONT_NAME, size: 16)!)!
        self.text = self.parseEmotions(text: attributedString)
    }
    
    private func parseEmotions(text: NSAttributedString) -> NSAttributedString {
        let bundle = Bundle.main
        guard let path = bundle.path(forResource: "emoticons.bundle/qqEmoticons", ofType: "plist") else {
            return text
        }
        guard let dic = NSDictionary(contentsOfFile: path), let _ = dic["emoticons"] as? NSArray else {
            return text
        }
        let directory = URL(fileURLWithPath: path).deletingLastPathComponent().path
        
        let attributedText = NSMutableAttributedString.init(attributedString: text)
        
        let emoticonResults = self.regexEmotions.matches(
            in: attributedText.string,
            options: [.reportProgress],
            range: NSRange(location: 0, length: attributedText.length)
        )
        
        var emoClipLength: Int = 0
        for emotion: NSTextCheckingResult in emoticonResults {
            if emotion.range.location == NSNotFound && emotion.range.length <= 1 {
                continue
            }
            var range: NSRange  = emotion.range
            range.location -= emoClipLength
            let realEmotion = attributedText.attributedSubstring(from: range)
            let imageName = TSEmojiDictionary[realEmotion.string]
            if imageName == nil {
                continue
            }

            /// 获取表情图片转成YYImage
            let image = UIImage(contentsOfFile: "\(directory)/\(imageName!)")
            if image == nil {
                continue
            }
            guard let imgData = image!.pngData() else { return NSAttributedString.init() }
            let images = YYImage(data: imgData, scale: 2)
        
            images?.preloadAllAnimatedImageFrames = true
            let imgView = YYAnimatedImageView(image: images)
            
           
            let att = NSMutableAttributedString.yy_attachmentString(withContent: imgView, contentMode: .center, attachmentSize: imgView.size, alignTo: UIFont(name: KQCHAT_FONT_NAME, size: 16)!, alignment: .center)
            
            attributedText.replaceCharacters(in: range, with: att)
            emoClipLength += range.length - att.length
            
        }
        
        return attributedText
        
    }
    
    /**
     正则：匹配 [哈哈] [笑哭。。] 表情
     */
    var regexEmotions: NSRegularExpression {
        get {
            let regularExpression = try! NSRegularExpression(pattern: "\\[[^\\[\\]]+?\\]", options: [.caseInsensitive])
            return regularExpression
        }
    }
    
    
    let TSEmojiDictionary = [
        "[微笑]" : "Expression_1",
        "[Smile]": "Expression_1",
        "/::)": "Expression_1",
        "[撇嘴]" : "Expression_2",
        "[Grimace]": "Expression_2",
        "/::~": "Expression_2",
        "[色]" : "Expression_3",
        "[Drool]" : "Expression_3",
        "/::B" : "Expression_3",
        "[发呆]" : "Expression_4",
        "[Scowl]" : "Expression_4",
        "/::|" : "Expression_4",
        "[得意]" : "Expression_5",
        "[CoolGuy]" : "Expression_5",
        "/:8-)" : "Expression_5",
        "[流泪]" : "Expression_6",
        "[Sob]" : "Expression_6",
        "/::<" : "Expression_6",
        "[害羞]" : "Expression_7",
        "[Shy]" : "Expression_7",
        "/::$" : "Expression_7",
        "[闭嘴]" : "Expression_8",
        "[Silent]" : "Expression_8",
        "/::X" : "Expression_8",
        "[睡]" : "Expression_9",
        "[Sleep]" : "Expression_9",
        "/::Z" : "Expression_9",
        "[大哭]" : "Expression_10",
        "[Cry]" : "Expression_10",
        "/::'(" : "Expression_10",
        "[尴尬]" : "Expression_11",
        "[Awkward]" : "Expression_11",
        "/::-|" : "Expression_11",
        "[发怒]" : "Expression_12",
        "[Angry]" : "Expression_12",
        "/::@" : "Expression_12",
        "[调皮]" : "Expression_13",
        "[Tongue]" : "Expression_13",
        "/::P" : "Expression_13",
        "[呲牙]" : "Expression_14",
        "[Grin]" : "Expression_14",
        "/::D": "Expression_14",
        "[惊讶]" : "Expression_15",
        "[Surprise]" : "Expression_15",
        "/::O": "Expression_15",
        "[难过]" : "Expression_16",
        "[Frown]" : "Expression_16",
        "/::(": "Expression_16",
        "[酷]" : "Expression_17",
        "[Ruthless]" : "Expression_17",
        "/::+": "Expression_17",
        "[囧]" : "Expression_18",
        "[blush]" : "Expression_18",
        "/:--b": "Expression_18",
        "[抓狂]" : "Expression_19",
        "[Scream]" : "Expression_19",
        "/::Q": "Expression_19",
        "[吐]" : "Expression_20",
        "[Puke]" : "Expression_20",
        "/::T": "Expression_20",
        "[偷笑]" : "Expression_21",
        "[Chuckle]" : "Expression_21",
        "/:,@P": "Expression_21",
        "[愉快]" : "Expression_22",
        "[Joyful]" : "Expression_22",
        "/:,@-D": "Expression_22",
        "[白眼]" : "Expression_23",
        "[Slight]" : "Expression_23",
        "/::d": "Expression_23",
        "[傲慢]" : "Expression_24",
        "[Smug]" : "Expression_24",
        "/:,@o": "Expression_24",
        "[饥饿]" : "Expression_25",
        "[Hungry]" : "Expression_25",
        "/::g": "Expression_25",
        "[困]" : "Expression_26",
        "[Drowsy]" : "Expression_26",
        "/:|-)": "Expression_26",
        "[惊恐]" : "Expression_27",
        "[Panic]" : "Expression_27",
        "/::!": "Expression_27",
        "[流汗]" : "Expression_28",
        "[Sweat]" : "Expression_28",
        "/::L": "Expression_28",
        "[憨笑]" : "Expression_29",
        "[Laugh]" : "Expression_29",
        "/::>": "Expression_29",
        "[悠闲]" : "Expression_30",
        "[Commando]" : "Expression_30",
        "/::,@": "Expression_30",
        "[奋斗]" : "Expression_31",
        "[Determined]" : "Expression_31",
        "/:,@f": "Expression_31",
        "[咒骂]" : "Expression_32",
        "[Scold]" : "Expression_32",
        "/::-S": "Expression_32",
        "[疑问]" : "Expression_33",
        "[Shocked]" : "Expression_33",
        "/:?": "Expression_33",
        "[嘘]" : "Expression_34",
        "[Shhh]" : "Expression_34",
        "/:,@x": "Expression_34",
        "[晕]" : "Expression_35",
        "[Dizzy]" : "Expression_35",
        "/:,@@": "Expression_35",
        "[疯了]" : "Expression_36",
        "[Tormented]" : "Expression_36",
        "/::8": "Expression_36",
        "[衰]" : "Expression_37",
        "[Toasted]" : "Expression_37",
        "/:,@!": "Expression_37",
        "[骷髅]" : "Expression_38",
        "[Skull]" : "Expression_38",
        "/:!!!": "Expression_38",
        "[敲打]" : "Expression_39",
        "[Hammer]" : "Expression_39",
        "/:xx": "Expression_39",
        "[再见]" : "Expression_40",
        "[Wave]" : "Expression_40",
        "/:bye": "Expression_40",
        "[擦汗]" : "Expression_41",
        "[Speechless]" : "Expression_41",
        "/:wipe": "Expression_41",
        "[抠鼻]" : "Expression_42",
        "[NosePick]" : "Expression_42",
        "/:dig": "Expression_42",
        "[鼓掌]" : "Expression_43",
        "[Clap]" : "Expression_43",
        "/:handclap": "Expression_43",
        "[糗大了]" : "Expression_44",
        "[Shame]" : "Expression_44",
        "/:&-(": "Expression_44",
        "[坏笑]" : "Expression_45",
        "[Trick]" : "Expression_45",
        "/:B-)": "Expression_45",
        "[左哼哼]" : "Expression_46",
        "[Bah！L]" : "Expression_46",
        "/:<@": "Expression_46",
        "[右哼哼]" : "Expression_47",
        "[Bah！R]" : "Expression_47",
        "/:@>": "Expression_47",
        "[哈欠]" : "Expression_48",
        "[Yawn]" : "Expression_48",
        "/::-O": "Expression_48",
        "[鄙视]" : "Expression_49",
        "[Pooh-pooh]" : "Expression_49",
        "/:>-|": "Expression_49",
        "[委屈]" : "Expression_50",
        "[Shrunken]" : "Expression_50",
        "/:P-(": "Expression_50",
        "[快哭了]" : "Expression_51",
        "[TearingUp]" : "Expression_51",
        "/::'|": "Expression_51",
        "[阴险]" : "Expression_52",
        "[Sly]" : "Expression_52",
        "/:X-)": "Expression_52",
        "[亲亲]" : "Expression_53",
        "[Kiss]" : "Expression_53",
        "/::*": "Expression_53",
        "[吓]" : "Expression_54",
        "[Wrath]" : "Expression_54",
        "/:@x": "Expression_54",
        "[可怜]" : "Expression_55",
        "[Whimper]" : "Expression_55",
        "/:8*": "Expression_55",
        "[菜刀]" : "Expression_56",
        "[Cleaver]" : "Expression_56",
        "/:pd": "Expression_56",
        "[西瓜]" : "Expression_57",
        "[Watermelon]" : "Expression_57",
        "/:<W>": "Expression_57",
        "[啤酒]" : "Expression_58",
        "[Beer]" : "Expression_58",
        "/:beer": "Expression_58",
        "[篮球]" : "Expression_59",
        "[Basketball]" : "Expression_59",
        "/:basketb": "Expression_59",
        "[乒乓]" : "Expression_60",
        "[PingPong]" : "Expression_60",
        "/:oo": "Expression_60",
        "[咖啡]" : "Expression_61",
        "[Coffee]" : "Expression_61",
        "/:coffee": "Expression_61",
        "[饭]" : "Expression_62",
        "[Rice]" : "Expression_62",
        "/:eat": "Expression_62",
        "[猪头]" : "Expression_63",
        "[Pig]" : "Expression_63",
        "/:pig": "Expression_63",
        "[玫瑰]" : "Expression_64",
        "[Rose]" : "Expression_64",
        "/:rose": "Expression_64",
        "[凋谢]" : "Expression_65",
        "[Wilt]" : "Expression_65",
        "/:fade": "Expression_65",
        "[嘴唇]" : "Expression_66",
        "[Lips]" : "Expression_66",
        "/:showlove": "Expression_66",
        "[爱心]" : "Expression_67",
        "[Heart]" : "Expression_67",
        "/:heart": "Expression_67",
        "[心碎]" : "Expression_68",
        "[BrokenHeart]" : "Expression_68",
        "/:break": "Expression_68",
        "[蛋糕]" : "Expression_69",
        "[Cake]" : "Expression_69",
        "/:cake": "Expression_69",
        "[闪电]" : "Expression_70",
        "[Lightning]" : "Expression_70",
        "/:li": "Expression_70",
        "[炸弹]" : "Expression_71",
        "[Bomb]" : "Expression_71",
        "/:bome": "Expression_71",
        "[刀]" : "Expression_72",
        "[Dagger]" : "Expression_72",
        "/:kn": "Expression_72",
        "[足球]" : "Expression_73",
        "[Soccer]" : "Expression_73",
        "/:footb": "Expression_73",
        "[瓢虫]" : "Expression_74",
        "[Ladybug]" : "Expression_74",
        "/:ladybug": "Expression_74",
        "[便便]" : "Expression_75",
        "[Poop]" : "Expression_75",
        "/:shit": "Expression_75",
        "[月亮]" : "Expression_76",
        "[Moon]" : "Expression_76",
        "/:moon": "Expression_76",
        "[太阳]" : "Expression_77",
        "[Sun]" : "Expression_77",
        "/:sun": "Expression_77",
        "[礼物]" : "Expression_78",
        "[Gift]" : "Expression_78",
        "/:gift": "Expression_78",
        "[拥抱]" : "Expression_79",
        "[Hug]" : "Expression_79",
        "/:hug": "Expression_79",
        "[强]" : "Expression_80",
        "[ThumbsUp]" : "Expression_80",
        "/:strong": "Expression_80",
        "[弱]" : "Expression_81",
        "[ThumbsDown]" : "Expression_81",
        "/:weak": "Expression_81",
        "[握手]" : "Expression_82",
        "[Shake]" : "Expression_82",
        "/:share": "Expression_82",
        "[胜利]" : "Expression_83",
        "[Peace]" : "Expression_83",
        "/:v": "Expression_83",
        "[抱拳]" : "Expression_84",
        "[Fight]" : "Expression_84",
        "/:@)": "Expression_84",
        "[勾引]" : "Expression_85",
        "[Beckon]" : "Expression_85",
        "/:jj": "Expression_85",
        "[拳头]" : "Expression_86",
        "[Fist]" : "Expression_86",
        "/:@@": "Expression_86",
        "[差劲]" : "Expression_87",
        "[Pinky]" : "Expression_87",
        "/:bad": "Expression_87",
        "[爱你]" : "Expression_88",
        "[RockOn]" : "Expression_88",
        "/:lvu": "Expression_88",
        "[NO]" : "Expression_89",
        "/:no": "Expression_89",
        "[OK]" : "Expression_90",
        "/:ok": "Expression_90",
        "[爱情]" : "Expression_91",
        "[InLove]" : "Expression_91",
        "/:love": "Expression_91",
        "[飞吻]" : "Expression_92",
        "[Blowkiss]" : "Expression_92",
        "/:<L>": "Expression_92",
        "[跳跳]" : "Expression_93",
        "[Waddle]" : "Expression_93",
        "/:jump": "Expression_93",
        "[发抖]" : "Expression_94",
        "[Tremble]" : "Expression_94",
        "/:shake": "Expression_94",
        "[怄火]" : "Expression_95",
        "[Aaagh!]" : "Expression_95",
        "/:<O>": "Expression_95",
        "[转圈]" : "Expression_96",
        "[Twirl]" : "Expression_96",
        "/:circle": "Expression_96",
        "[磕头]" : "Expression_97",
        "[Kotow]" : "Expression_97",
        "/:kotow": "Expression_97",
        "[回头]" : "Expression_98",
        "[Dramatic]" : "Expression_98",
        "/:turn": "Expression_98",
        "[跳绳]" : "Expression_99",
        "[JumpRope]" : "Expression_99",
        "/:skip": "Expression_99",
        "[投降]" : "Expression_100",
        "[Surrender]" : "Expression_100",
        "/:oY": "Expression_100"
    ]

    
}
